/** @jsxImportSource @emotion/react */
import { jsx, css, keyframes } from "@emotion/react";
import * as React from "react";
import PropTypes from "prop-types";
import { Global } from "@emotion/react";
import { useSpring, animated } from "react-spring";
import {
    useTheme,
    VisuallyHidden,
    IconAlertCircle, IconChevronDown,
    Text, LabelText,
    StateType, IconMoreVertical,
} from "customize-easy-ui-component";
// import {Bounds, useMeasure} from "customize-easy-ui-component/esm/Hooks/use-measure";
import {useFocusElement} from "customize-easy-ui-component/esm/Hooks/use-focus-trap";
import {isHoverEnabled} from "customize-easy-ui-component/esm/Hooks/hover-enabled";
import {List2Item} from "./List";
import {DdMenu, DdMenuItem} from "./DropdownMenu";
import {Menu2Item} from "./Menu";
import {Dragable, } from "../../../../customize-easy-ui-component/src/Dragable";
import {Bounds} from "@use-gesture/react";
import {useWindowSize} from "customize-easy-ui-component/esm/Hooks/use-window-size";
import {safeBind} from "customize-easy-ui-component/esm/Hooks/compose-bind";


const spin = keyframes`
  to { 
    transform: rotate(360deg); 
  }
`;

const sizeStyles = {
  xs: css({ width: "1rem", height: "1rem" }),
  sm: css({ width: "3rem", height: "3rem" }),
  md: css({ width: "5rem", height: "5rem" }),
  lg: css({ width: "8rem", height: "8rem" }),
  xl: css({ width: "12rem", height: "12rem" })
};

interface DragPinnerProps extends React.HTMLAttributes<HTMLDivElement> {
    /**延迟关闭执行 onRequestPress；    =0不会自己关闭执行。
    * delay这段时间内，也没办法点击页面按钮的,也要同步等待后端的应答返回来，用户才能继续操作。
    *  */
    delay?: number;
    size?: "xs" | "sm" | "md" | "lg" | "xl";
    /** Attempt to center the spinner in the parent element */
    center?: boolean;
    /** Use an optional label */
    label?: string;
    //要不要显示出来！
    doing: boolean;
    /**点击关闭 或者任意其它的回调处理  */
    onRequestPress: () => void;
    //限制游走的区域          MutableRefObject<null>;
    //内部直接限制
    bounds?: Bounds | HTMLElement | { current: HTMLElement | null };
}

/**【预留】 测试拖拽移动组件的能力；  还不适合有滚动条页面。 【思路】把局部内容放大和一块一块地定位，相对于某个Div-Id-key定位。
 * <Global 添加以后：上拉完成。
 * 基础参看 https://github.com/bmcmahen/react-gesture-responder 该包实现基本状态管理和浏览器回调绑定。
 * 按钮，菜单 和 ListItem 实际使用到:-> useTouchable :->最后底层会用 useGestureResponder的。
 * 手机状态下是无法上拉的{背景会滚}:必须设置overflowY: 'hidden'才可以上拉。 鼠标拉拽可能必须再次点下才能最终释放变位置显示最终出现onEnd{有可能是丢失事件消息}。
 *防止背景滚动 https://www.it610.com/article/1294815963329404928.htm 需要对ref.Div的ontouchstart、ontouchmove两个都加上preventDefault();
* */
export const DragablePinner: React.FunctionComponent<DragPinnerProps> = (
    {
    delay = 0,
    size = "md",
    center=true,
    label,
    doing=false,
    bounds,
    onRequestPress,
  ...other
}) => {
  const theme = useTheme();
    const {innerHeight, innerWidth,}= useWindowSize();
     //嵌入开始
    const ref = React.useRef<HTMLDivElement | null>(null);
    useFocusElement(ref, false);
    //初始位置，?可以保存位置信息到 localStorage(“”，{}):  ?非固定0,0位置：计算相对偏移区域？
    const [iconxy, setIconxy] = React.useState({x:0, y:0});
    const windowBouds={top:0-innerHeight!, bottom: 0, left:0-innerWidth!, right: 0};

//嵌入结束 :【严重问题】传入的onRequestClose是会变动的，正好定时器执行后onRequestClose必然变，所以加入依赖项后，这里相当于死循环，开了关关了又再开!!useEffect事实死循环?
    React.useEffect(() => {
       if(delay===0)    return;
       const timer= setTimeout(() => {
                     onRequestPress();
            }, delay);

        return () => {
            clearTimeout(timer);
        };
    }, [onRequestPress, delay]);

    if(!doing)  return null;

    return (
     <React.Fragment>
         <Global
             styles={{
                 html: {
                    //overflowY: active? 'hidden' : undefined,
                 }
             }}
         />
         <Dragable className="DragPinner__IconTrgger"
                   bounds={bounds? bounds : windowBouds}
                   css={{
                 color: theme.colors.text.default,
                 textAlign: "center",
                 display: "inline-block",
                 margin: 'auto',
                 zIndex: theme.zIndices.waituntil,
                 position: 'fixed',       //'absolute', 跟随滚动
                 // top: `${iconxy.y}px`,
                 // left: `${iconxy.x}px`,
                 bottom: `${iconxy.y}px`,
                 right: `${iconxy.x}px`,
             }}
                   {...safeBind(
             {
                 onClick: (e: React.MouseEvent) => {
                     //可以其它操作一起执行。
                     onRequestPress();
                 },
                 onKeyDown: (e: React.KeyboardEvent) => {    //#实际没法捕捉到了?
                   if (e.key === "Escape") {
                       e.stopPropagation();
                       onRequestPress();
                   }
                 },
               },
               other
            )}
           >
                 <div
                     className="DragPinner__BoundRct"
                     ref={ref}
                     css={[
                         css`
                        display: inline-block;
                        vertical-align: text-bottom;
                        border: 0.15em solid currentColor;
                        border-right-color: transparent;
                        border-radius: 50%;
                        animation: ${spin} 0.75s linear infinite;
                      `,
                         sizeStyles[size]
                     ]}
                 >
                 </div>

                 {label ? (
                     <Text
                         className="DragPinner__label"
                         wrap={false}
                         css={{ display: "block", marginTop: theme.spaces.sm }}
                         variant="subtitle"
                     >
                         {label}
                     </Text>
                 ) : (
                     <VisuallyHidden>{"Loading"}</VisuallyHidden>
                 )}
         </Dragable>
   </React.Fragment>
  );
};

